<?php

namespace common\helps;

use app\models\AsrCustomer;
use app\models\AsrFiles;
use app\models\AsrKeyword;
use app\models\AsrKeywordClassify;
use app\models\AsrKeywordEndClassify;
use app\models\AsrKeywordXtlcClassify;
use app\models\AsrKeywordYwlcClassify;
use app\models\AsrPlan;
use yii\helpers\ArrayHelper;

class AsrSearch
{

    /**
     * 查找关键字
     * @param $result
     * 以下是接收到的数据
     * $b['plan_id'] = 1;
     * $b['state'] = 0;
     * $b['phone_num'] = 4565;
     * $b['customer_id'] = 4565;
     * $b['audio_id'] = 97;
     * $b['mobile_id'] = 97;
     * $b['call_position'] = 97;
     * $b['str'] = '按时打算';
     */
    public function search_keyword($data)
    {
        try{
            //连接redis
            //$redis = \Yii::$app->redis;
            $redis = \Yii::$app->cache;
            $parms = $data["audio_id"];
            $parms = explode("_",$parms);
            $parms = setArray($parms);
            $asrResult = json_decode($data["asrResult"]);
            $asrResult = $asrResult->text;
            //获取当前正在拨打的电话号码
            //正在拨打当前号码
            //获取当前拨打到了哪一个电话
            $asrCustomer = AsrCustomer::find()->select('customer_id,phone_num,mobile_id,state')->where(['customer_id'=>$parms['customer_id']])->one();
            //$redis->set("asr_audio:".$parms['audio_id'].":asr_plan:plan_id=".$parms['plan_id'].":cti_sleeping",0);//修改状态为正在打电话
            //将结果分成各种词语
            Tools::l("识别结果：".$asrResult);
            $res = $this->keywordSplit($asrResult,0,1);
            //将结果切割成数组形式
            $resArr = explode("|",$res);//比如说是   你|你是|你是谁
            $resArr = array_filter($resArr);
            $asrKeywords = '';
            foreach ($resArr as $k=>$v){
                //模糊查询到相应的关键字的那一条数据记录
                $asrKeywords = AsrKeyword::find()->select('*')->where("content like %;".$asrResult.";%")->andFilterWhere(['classify_id'=>$parms['classify_id']])->one();
            }
            //没有检测到这个关键字
            if (empty($asrKeywords)){
                $asrKeywords = AsrKeyword::find()->select('*')->where("content = ''")->andFilterWhere(['classify_id'=>$parms['classify_id']])->one();
            }
            //没有设置相应的关键字
            if (!empty($asrKeywords)){
                echo "查询关键字失败，没有设置相应的关键字！";
                exit();
            }
            //拿到查找到的下一个节点的流程id
            switch ($asrKeywords->next_classify_type){
                case 0://主流程
                    $nextClassify = AsrKeywordClassify::findOne($asrKeywords->next_classify_id);
                    break;
                case 1://业务流程
                    $nextClassify = AsrKeywordYwlcClassify::findOne($asrKeywords->next_classify_id);
                    break;
                case 2://系统流程
                    $nextClassify = AsrKeywordXtlcClassify::findOne($asrKeywords->next_classify_id);
                    break;
                case 3://结束流程
                    $nextClassify = AsrKeywordEndClassify::findOne($asrKeywords->next_classify_id);
                    break;
            }
            //拿到下一个流程的文件的id
            $nextFileId= $nextClassify->file_id;
            $nextFileIdArr = array_filter(explode(",",$nextFileId));
            //表示文件为空，
            if (!(count($nextFileIdArr)>0)){
                echo "文件为空，请新增该流程需要播放的流程";
                exit();
            }
            //拿到第一个需要播放的文件
            $asrFiles = AsrFiles::findOne($nextFileIdArr[0]);

            //将数据包装
            $data2["plan_id"] = $parms["plan_id"];//计划ID
            $data2["audio_id"] = $parms["audio_id"];//计划ID
            $data2["call_state"] = $asrKeywords->next_classify_type;//打电话的状态标识,结束或者继续
            $data2["customer_id"] = $asrCustomer->customer_id;//需要拨打出去的电话的ID
            $phone_num = $asrCustomer->phone_num;
            $filepath = "E:/Recordfile/abc.wav";//需要播放的文件路径
            //$filepath = $asrFiles->filepath;
            $data2["classify_type"] = $asrKeywords->next_classify_type;//下一个节点的类型
            $data2["classify_id"] = $nextClassify->keyword_classify_id;//本次流程的id

            //拿到之前的CTI的结果
            $from_cti = $redis->get("asr_audio:".$parms['audio_id'].":asr_plan:plan_id=".$parms['plan_id'].":from_cti");
            $from_cti = json_decode($from_cti);
            //将数据发送给CTI
            $this->actionSendpost('http://192.168.2.247:8000/playwav?audio_id='.implode("_",$data2).'chid='.$from_cti->chid.'&filepath='.$filepath.'&call_state='.$asrKeywords->next_classify_type,$data2);
        }catch (\Exception $exception){
            Tools::l($exception);
            exit();
        }
    }

    /**
     * 接收到CTI端的电话挂断的信号，然后就写查找下一个电话号码
     */
    public function hangupPhone($data)
    {
        try{
            //连接redis
            //$redis = \Yii::$app->redis;
            $redis = \Yii::$app->cache;
            $parms = $data["audio_id"];
            $parms = explode("_",$parms);
            $parms = setArray($parms);

            //挂断当前号码
            //获取当前拨打到了哪一个电话
            $redis->set("asr_audio:".$parms['audio_id'].":asr_plan:plan_id=".$parms['plan_id'].":cti_sleeping",1);//修改状态为正在打电话
            $asrPlan = AsrPlan::findOne($parms['plan_id']);
            //睡眠一段时间
            $interval_time = $asrPlan->interval_time;
            sleep(empty($interval_time)?0:$interval_time);
            //检查当前号码是否为当前列表的最后一个号码
            //下一个需要播放的手机号码
            $asrCustomer= AsrCustomer::find()->select('phone_num,mobile_id')->where(['>','customer_id',$parms['customer_id']])->andFilterWhere(['mobile_id'=>$parms['mobile_id']])->one();
            //如果下一个电话号码为空，表示已经打完了一个循环了。要重新重头查找一次
            if (empty($asrCustomer)){
                $asrCustomer= AsrCustomer::find()->select('phone_num,mobile_id')->Where(['mobile_id'=>$parms['mobile_id']])->one();
            }
            //下一个需要播放的录音文件
            //根据audio_id 以及 start字段查找开场白
            $asrKeywordClassify = AsrKeywordClassify::find()->select('keyword_classify_id,file_id')->where(['audio_id'=>$asrPlan->audio_id,'start'=>1])->one();
            //拿到文件的ID
            $files_id = $asrKeywordClassify->file_id;
            //拿到文件的对象
            $asrFiles = AsrFiles::find()->select("filepath")->where("files_id=".$files_id)->one();
            //流程开始循环传输数据
            $data2["plan_id"] = $parms["plan_id"];//计划ID
            $data2["audio_id"] = $parms["audio_id"];//计划ID
            $data2["call_state"] = 0;//打电话的状态标识,结束或者继续
            $data2["customer_id"] = $asrCustomer->customer_id;//需要拨打出去的电话的ID
            $phone_num = $asrCustomer->phone_num;
            $filepath = "E:/Recordfile/abc.wav";//需要播放的文件路径
            //$filepath = $asrFiles->filepath;
            $data2["classify_type"] = 0;//下一个节点的类型
            $data2["classify_id"] = $asrKeywordClassify->keyword_classify_id;//本次流程的id

            //拿到之前的CTI的结果
            $from_cti = $redis->get("asr_audio:".$parms['audio_id'].":asr_plan:plan_id=".$parms['plan_id'].":from_cti");
            $from_cti = json_decode($from_cti);
            //发生数据给CTI端
            $this->actionSendpost('http://192.168.2.247:8000/playwav?audio_id='.implode("_",$data2).'chid='.$from_cti->chid.'&filepath='.$filepath.'&call_state='.$asrKeywords->next_classify_type,$data2);
        }catch (\Exception $exception){
            Tools::l($exception);
            exit();
        }
    }


    /**
     * 将接收到的数组格式化
     * @param $arr
     * @return array
     */
    public function setArray($arr){
        $data = [];
        if (count($arr)>6){
            $data["plan_id"] = $arr[0];//计划ID
            $data["audio_id"] = $arr[1];//计划ID
            $data["from_php_cti_state"] = $arr[2];//本次流程的id
            $data["customer_id"] = $arr[3];//需要拨打出去的电话的ID
            $data["classify_type"] = $arr[4];//节点的类型
            $data["classify_id"] = $arr[5];
            $data["chid"] = $arr[6];//节点的类型
        }
        return $data;
    }


    //数据发送
    public function actionSendpost($url,$post_data)
    {
        try{
            $post_data = http_build_query($post_data);
            $options = array(
                'http' => array(
                    'method' => 'POST',
                    'header' => 'Content-type:application/x-www-form-urlencoded',
                    'content' => $post_data,
                    'timeout' => 1000// 超时时间（单位:s）
                )
            );
            $context = stream_context_create($options);
            $res = file_get_contents($url, false, $context);
            $resObj = json_decode($res);
            Tools::l("接收CTI发送的数据:".$resObj);
            return $resObj;
        }catch (\Exception $exception){
            Tools::l($exception);
            exit();
        }
    }


    //循环字符串
    static $keyword_res = '';
    public function keywordSplit($keyword,$start,$length,$res=""){
        if ($keyword == "" || $start == mb_strlen($keyword)){
            AsrSearch::$keyword_res = $res;
            return AsrSearch::$keyword_res;
        }else {
            if ($length == mb_strlen($keyword)-$start){
                $temp = mb_substr($keyword, $start, $length);
                $res .= $temp."|";
                $start++;
                $length=1;
                 $this->keywordSplit($keyword,$start,$length,$res);
            }else{

                $temp = mb_substr($keyword, $start, $length);
                $length++;
                $res .= $temp."|";
                $this->keywordSplit($keyword,$start,$length,$res);
            }
        }
    }
}